﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using System.IO;

namespace WebUI.EditPages
{
    public partial class EditProduct : BasePage
    {
        Products product;
        int productID;
        string mode;

        string SessionID
        {
            get { return ViewState["SessionID"] != null ? ViewState["SessionID"].ToString() : ""; }
            set {  ViewState["SessionID"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            if (Request.QueryString[KEY] == null && SessionID == "")
            {
                SessionID = Guid.NewGuid().ToString();
                Products p = new Products();
                Session[SessionID] = p;
                return;
            }
            else if(Request.QueryString[KEY] != null)
                SessionID = Request.QueryString[KEY];

            if (Request.QueryString[MODE] == null)
            {
                CloseDlg(0);
                return;
            }

            mode = Request.QueryString[MODE];

            if (Request.QueryString[ID] == null && (mode == EDIT_MODE || mode == VIEW_MODE))
            {
                CloseDlg(0);
                return;
            }

            product = (Products)Session[SessionID];
            string oldFilter = product.Filter;

            productID = Request.QueryString[ID] != null ? int.Parse(Request.QueryString[ID]) : 0;
            if (mode != ADD_MODE)
                product.Filter = Products.ColumnNames.ID + "=" + productID.ToString();
            else
            {
                if (!IsPostBack)
                {
                    editProduct.SoldQuantity = 0;
                    editProduct.Quantity = 0;
                }
                btnSave.Enabled = false;
            }

            if (!IsPostBack && product.RowCount > 0 && mode != ADD_MODE)
                LoadInfo();

            product.Filter = oldFilter;
        }

        public void btnSave_OnClick(Object sender, EventArgs e)
        {
            Save();
            if (Request.QueryString[KEY] == null)
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", SessionID), true); 
            else
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("window.returnValue={0};", 1), true); 
        }

        private bool Save()
        {
            string oldFilter = product.Filter;
            try
            {
                if (mode == ADD_MODE)
                {
                    product.AddNew();
                    product.BranchID = Branches.CurrentBranchID;
                    product.Deleted = false;
                }
                else
                {
                    product.Filter = Products.ColumnNames.ID + "=" + productID;
                }

                if (editProduct.CategoryID > 0)//when saving foreign key, remember to check condition or we may get confliction
                    product.CategoryID = editProduct.CategoryID;

                product.LastModifiedByUser = SessionUser.ID;
                product.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                product.ProductName = editProduct.ProductName;
                product.Description = editProduct.Description;
                product.Cost = editProduct.Cost > 0 ? editProduct.Cost : 0;
                product.DealerPrice = editProduct.DealerPrice > 0 ? editProduct.DealerPrice : 0;
                product.SalePrice = editProduct.SalePrice > 0 ? editProduct.SalePrice : 0;
                product.PartnerPrice = editProduct.PartnerPrice > 0 ? editProduct.PartnerPrice : 0;
                if (editProduct.RegularPrice >= 0)
                    product.RegularPrice = editProduct.RegularPrice;
                else
                    product.s_RegularPrice = "";
                

                if (editProduct.BrandID > 0)//when saving foreign key, remember to check condition or we may get confliction
                    product.BrandID = editProduct.BrandID;
                product.BarCode = editProduct.BarCode;
                product.IMEIAvailable = editProduct.IMEIAvailable;
                if (!product.IMEIAvailable)//only update quantity when it is non IMEI product
                    product.Quantity = editProduct.Quantity > 0 ? editProduct.Quantity : 0;
                else if (mode == ADD_MODE)
                    product.Quantity = 0;
                product.SoldQuantity = editProduct.SoldQuantity > 0 ? editProduct.SoldQuantity : 0;
                product.GST = editProduct.GST;
                product.IsHotProduct = editProduct.HotProduct;
                product.IsNewArrival = editProduct.NewArrival;
                product.IsHomeProduct = editProduct.HomeVisible;
                product.IsDealerOnly = editProduct.DealerOnly;

                product.Save();

                if (mode == ADD_MODE)
                {
                    product.StockKey = product.ID;
                    product.Save();
                }

                product.Filter = oldFilter;
                ((Popup)Master).ShowMessage("Saved");
                return true;
            }
            catch (Exception ex)
            {
                product.RejectChanges();
                product.Filter = oldFilter;

                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("EditProduct.aspx.cs", "Save", ex.StackTrace);
                return false;
            }
        }

        private void LoadInfo()
        {
            try
            {
                if (!product.IsColumnNull(Products.ColumnNames.CategoryID))
                    editProduct.CategoryID = product.CategoryID;
                if (!product.IsColumnNull(Products.ColumnNames.ProductName))
                    editProduct.ProductName = product.ProductName;
                if (!product.IsColumnNull(Products.ColumnNames.Description))
                    editProduct.Description = product.Description;
                if (!product.IsColumnNull(Products.ColumnNames.Cost))
                    editProduct.Cost = product.Cost > 0 ? product.Cost : 0;
                if (!product.IsColumnNull(Products.ColumnNames.DealerPrice))
                    editProduct.DealerPrice = product.DealerPrice > 0 ? product.DealerPrice : 0;
                if (!product.IsColumnNull(Products.ColumnNames.SalePrice))
                    editProduct.SalePrice = product.SalePrice > 0 ? product.SalePrice : 0;
                if (!product.IsColumnNull(Products.ColumnNames.PartnerPrice))
                    editProduct.PartnerPrice = product.PartnerPrice > 0 ? product.PartnerPrice : 0;
                if (!product.IsColumnNull(Products.ColumnNames.RegularPrice))
                    editProduct.RegularPrice = product.RegularPrice > 0 ? product.RegularPrice : 0;

                ProductImages img = ProductImages.GetDefaultPicture(product.ID);

                if (img.RowCount > 0 && !img.IsColumnNull(ProductImages.ColumnNames.OriginalUrl))
                    editProduct.Picture = POSSystem.BLL.Utilities.GetProductImageUrl(img.OriginalUrl);

                if (img.RowCount > 0 && !img.IsColumnNull(ProductImages.ColumnNames.ThumbUrl))
                    editProduct.Thumbnail = POSSystem.BLL.Utilities.GetProductImageUrl(img.ThumbUrl);
                
                
                if (!product.IsColumnNull(Products.ColumnNames.BrandID))
                    editProduct.BrandID = product.BrandID;
                if (!product.IsColumnNull(Products.ColumnNames.BarCode))
                    editProduct.BarCode = product.BarCode;
                if (!product.IsColumnNull(Products.ColumnNames.IMEIAvailable))
                    editProduct.IMEIAvailable = product.IMEIAvailable;
                if (!product.IsColumnNull(Products.ColumnNames.Quantity))
                    editProduct.Quantity = product.Quantity > 0 ? product.Quantity : 0;
                if (!product.IsColumnNull(Products.ColumnNames.SoldQuantity))
                    editProduct.SoldQuantity = product.SoldQuantity > 0 ? product.SoldQuantity : 0;
                if (!product.IsColumnNull(Products.ColumnNames.GST))
                    editProduct.GST = product.GST;
                if (!product.IsColumnNull(Products.ColumnNames.IsHotProduct))
                    editProduct.HotProduct = product.IsHotProduct;
                if (!product.IsColumnNull(Products.ColumnNames.IsNewArrival))
                    editProduct.NewArrival = product.IsNewArrival;
                if (!product.IsColumnNull(Products.ColumnNames.IsHomeProduct))
                    editProduct.HomeVisible = product.IsHomeProduct;
                if (!product.IsColumnNull(Products.ColumnNames.IsDealerOnly))
                    editProduct.DealerOnly = product.IsDealerOnly;
            }
            catch (Exception ex)
            {
                ((Popup)Master).ShowErrorMessage(ex.Message);
                ErrorLog.WriteToFile("EditProduct.aspx.cs", "LoadInfo", ex.StackTrace);
            }
        }

        public void btnSaveAndClose_OnClick(Object sender, EventArgs e)
        {
            if (Save())
            {
                if (Request.QueryString[KEY] == null)
                    CloseDlg(SessionID);
                else
                    CloseDlg(1);
            }
        }
    }
}
